package summer.codegenerator.common.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/**
 * 
 * 
 * @author 蒋振
 * @since 2019年7月11日 下午2:55:33
 */
public class PropertiesUtil {

	private static Map<String, Properties> pathProperties = new HashMap<String, Properties>();

	/**
	 * 
	 * @param path          文件路径
	 *          /sys.properties
	 *          /conf/conf.properties
	 * @param reload        是否重新加载
	 * @return
	 * @throws IOException 
	 */
	public synchronized static Properties loadPropertiesFromFile(String path, Boolean reload) throws IOException {
		if (reload || pathProperties.get(path) == null) {
			Resource resource = new ClassPathResource(path);
			Properties props = PropertiesLoaderUtils.loadProperties(resource);
			pathProperties.put(path, props);
		}
		return pathProperties.get(path);
	}

	/**
	 * 
	 * @param path          文件路径
	 * @return
	 * @throws IOException 
	 */
	public static Properties loadPropertiesFromFile(String path) throws IOException {
		return loadPropertiesFromFile(path, false);
	}

	public static Properties loadSysPropertiesFromFile() throws IOException {
		return loadPropertiesFromFile("/sys.properties", false);
	}

	public static String getProp(String path, String key) throws IOException {
		Object obj = loadPropertiesFromFile(path, false).get(key);
		if (obj != null) {
			return obj.toString();
		}
		return null;
	}

	public static String getSysProp(String key) throws IOException {
		Object obj = loadPropertiesFromFile("/sys.properties", false).get(key);
		if (obj != null) {
			return obj.toString();
		}
		return null;
	}
}
